package io.clayton.miep.utils;

import io.clayton.miep.core.BaseVO;
import io.clayton.miep.core.RuntimeContext;
import io.clayton.miep.core.SessionBean;

import java.util.List;
import java.util.Map;

/**
 * 为审计字段赋值工具类
 */
public class FieldUtils {
	
	public static final int SELECT = 0;
	public static final int INSERT = 100;
	public static final int UPDATE = 200;
	public static final int DELETE = 300;
	
	private static final String ANONYMOUS_IDENTITY = "~";

	private static final String CREATOR_FIELD = "creator";
	private static final String CREATETIME_FIELD = "createtime";
	private static final String MODIFIER_FIELD = "modifier";
	private static final String MODIFYTIME_FIELD = "modifytime";
	
	/**
	 * 为单个对象添加或修改的审计字段赋值  拦截参数为单个对象
	 * @param obj
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static void setFieldValue(BaseVO obj, int str) {
		if(INSERT == str) {
			if (obj.getId() == null) {
				obj.setId(IDGenerator.generate());
			}
			obj.setCreator(getUserAccount());
			obj.setCreatetime(getTimestamp());
		} else {
			obj.setModifier(getUserAccount());
			obj.setModifytime(getTimestamp());
		}
	}
	
	/**
	 * 拦截参数为Map
	 * @param object
	 * @param insert
	 */
	public static void setFieldValue(Map<String, Object> map, int str) {
		if(INSERT == str) {
			if (map.get("id") == null) {
				map.put("id", IDGenerator.generate());
			}
			map.put(CREATOR_FIELD, getUserAccount());
			map.put(CREATETIME_FIELD, getTimestamp());
		} else {
			map.put(MODIFIER_FIELD, getUserAccount());
			map.put(MODIFYTIME_FIELD, getTimestamp());
		}
	}
	
	/**
	 * 批量添加，批量赋值  拦截参数为List
	 * @param object
	 * @param insert
	 * @throws Exception 
	 */
	public static void setFieldValue(List<Object> list, int str) throws Exception {
		for (int i = 0; i < list.size(); i++) {
			Object obj = list.get(i);
			if(obj instanceof Map){
				// list存放的类型为map
				setFieldValue((Map) obj, str);
			} else if (obj instanceof BaseVO) {
				// list存放的类型为对象
				setFieldValue((BaseVO) obj, str);
			}
			
		}
	}
	
	private static String getUserAccount() {
		SessionBean sessionBean = RuntimeContext.getSessionBean();
		if (sessionBean != null && sessionBean.getUserAccount() != null) {
			return sessionBean.getUserAccount();
		} else {
			return ANONYMOUS_IDENTITY;
		}
	}
	
	private static String getTimestamp() {
		return String.valueOf(System.currentTimeMillis());
	}
	
}
